package com.addcn.pushlibrary;

import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import cn.jpush.android.api.JPushInterface;
import com.addcn.pushlibrary.bean.PMessage;
import com.addcn.pushlibrary.fcm.LFcmManager;
import com.addcn.pushlibrary.huawei.LHuaweiManger;
import com.addcn.pushlibrary.jpush.LJpushManager;
import com.addcn.pushlibrary.jpush.LJpushReceiver;
import com.addcn.pushlibrary.oppo.LOppoManger;
import com.addcn.pushlibrary.utils.LBitmapUtil;
import com.addcn.pushlibrary.utils.LRomUtil;
import com.addcn.pushlibrary.utils.ParcelablesUtil;
import com.addcn.pushlibrary.utils.catchs.LSharedUtil;
import com.addcn.pushlibrary.vivo.LVivoManger;
import com.addcn.pushlibrary.xiaomi.LMiManger;
import com.google.firebase.FirebaseApp;
import com.google.firebase.messaging.FirebaseMessaging;
import com.huawei.hms.aaid.HmsInstanceId;

/**
 * author:luwenbo
 * created on date : 2019-05-15
 * content:
 * describe:
 */
public class LPush {
    private static String TAG = "LPush";
    private static LPush lPush = null;
    private static Context mContext;
    private LRomUtil.ROM_TYPE type = LRomUtil.ROM_TYPE.JPush;
    private LConfiguration configuration;

    public static LPush getInstance(Context context) {
        if (lPush == null) {
            mContext = context;
            lPush = new LPush();
        }
        return lPush;
    }

    public void init(Application application, LConfiguration configuration) {
        LRomUtil.prepare(mContext);
        type = LRomUtil.getRomType();
        this.configuration = configuration;
        Log.d(TAG,"type:"+type);
        switch (type) {
            case FCM:
                FirebaseApp.initializeApp(mContext);
                LFcmManager.init(mContext);
                LJpushManager.stopPush(mContext);
                LHuaweiManger.Companion.stopPush(mContext);
                break;
            case Huawei:
                if (!configuration.hwAppId.equals("")){
                    LHuaweiManger.Companion.init(application, configuration);
                }else if (LRomUtil.isFcm(mContext)){
                    type = LRomUtil.ROM_TYPE.FCM;
                    FirebaseApp.initializeApp(mContext);
                    LFcmManager.init(mContext);
                    LJpushManager.stopPush(mContext);
                    LHuaweiManger.Companion.stopPush(mContext);
                }else{
                    type = LRomUtil.ROM_TYPE.JPush;
                    LJpushManager.init(mContext, configuration);
                    LHuaweiManger.Companion.stopPush(mContext);
                }
                break;
            case Mi:
                if (!configuration.xmAppId.equals("")){
                    LMiManger.Companion.init(application, configuration);
                }else if (LRomUtil.isFcm(mContext)){
                    type = LRomUtil.ROM_TYPE.FCM;
                    FirebaseApp.initializeApp(mContext);
                    LFcmManager.init(mContext);
                    LJpushManager.stopPush(mContext);

                }else{
                    type = LRomUtil.ROM_TYPE.JPush;
                    LJpushManager.init(mContext, configuration);
                }
                LHuaweiManger.Companion.stopPush(mContext);
                break;
            case OPPO:
                if (!configuration.oppoAppId.equals("")){
                    LOppoManger.Companion.init(application,configuration);
                    if (!LOppoManger.Companion.isSupportPush()){
                        if (LRomUtil.isFcm(mContext)){
                            type = LRomUtil.ROM_TYPE.FCM;
                            FirebaseApp.initializeApp(mContext);
                            LFcmManager.init(mContext);
                            LJpushManager.stopPush(mContext);
                        }else{
                            type = LRomUtil.ROM_TYPE.JPush;
                            LJpushManager.init(mContext, configuration);

                        }
                    }
                }else if (LRomUtil.isFcm(mContext)){
                    type = LRomUtil.ROM_TYPE.FCM;
                    FirebaseApp.initializeApp(mContext);
                    LFcmManager.init(mContext);
                    LJpushManager.stopPush(mContext);

                }else{
                    type = LRomUtil.ROM_TYPE.JPush;
                    LJpushManager.init(mContext, configuration);
                }
                LHuaweiManger.Companion.stopPush(mContext);
                break;
            case VIVO:
                if (!configuration.vivoAppId.equals("")){
                    LVivoManger.Companion.init(application,configuration);
                    if (!LVivoManger.Companion.isSupport(mContext)){
                        if (LRomUtil.isFcm(mContext)){
                            type = LRomUtil.ROM_TYPE.FCM;
                            FirebaseApp.initializeApp(mContext);
                            LFcmManager.init(mContext);
                            LJpushManager.stopPush(mContext);
                        }else{
                            type = LRomUtil.ROM_TYPE.JPush;
                            LJpushManager.init(mContext, configuration);
                        }
                    }
                }else if (LRomUtil.isFcm(mContext)){
                    type = LRomUtil.ROM_TYPE.FCM;
                    FirebaseApp.initializeApp(mContext);
                    LFcmManager.init(mContext);
                    LJpushManager.stopPush(mContext);
                }else{
                    type = LRomUtil.ROM_TYPE.JPush;
                    LJpushManager.init(mContext, configuration);
                }
                LHuaweiManger.Companion.stopPush(mContext);
                break;
            case JPush:
            default:
                LJpushManager.init(mContext, configuration);
                LHuaweiManger.Companion.stopPush(mContext);
                break;
        }
    }


    public String getToken() {
        String pushToken = "";
        switch (type) {
            case FCM:
                pushToken = LSharedUtil.getString(mContext, "l_fcm_token");
                break;
            case Huawei:
                if (!configuration.hwAppId.equals("")){
                    pushToken = LSharedUtil.getString(mContext, "l_huawei_token");
                }else if (LRomUtil.isFcm(mContext)){
                    pushToken = LSharedUtil.getString(mContext, "l_fcm_token");
                }else{
                    if (!JPushInterface.isPushStopped(mContext)) {
                        pushToken = JPushInterface.getRegistrationID(mContext);
                    }
                }
                break;
            case Mi:
                if (!configuration.xmAppId.equals("")){
                    pushToken = LMiManger.Companion.getRegisterId(mContext);
                }else if (LRomUtil.isFcm(mContext)){
                    pushToken = LSharedUtil.getString(mContext, "l_fcm_token");
                }else{
                    if (!JPushInterface.isPushStopped(mContext)) {
                        pushToken = JPushInterface.getRegistrationID(mContext);
                    }
                }
                break;
            case OPPO:
                if (!configuration.oppoAppId.equals("")){
                    pushToken = LOppoManger.Companion.getRegisterId() == null?"":LOppoManger.Companion.getRegisterId();
                }else if (LRomUtil.isFcm(mContext)){
                    pushToken = LSharedUtil.getString(mContext, "l_fcm_token");
                }else{
                    if (!JPushInterface.isPushStopped(mContext)) {
                        pushToken = JPushInterface.getRegistrationID(mContext);
                    }
                }
                break;
            case VIVO:
                if (!configuration.vivoAppId.equals("")){
                    pushToken = LVivoManger.Companion.getRegisterId(mContext) == null?"":LVivoManger.Companion.getRegisterId(mContext);
                }else if (LRomUtil.isFcm(mContext)){
                    pushToken = LSharedUtil.getString(mContext, "l_fcm_token");
                }else{
                    if (!JPushInterface.isPushStopped(mContext)) {
                        pushToken = JPushInterface.getRegistrationID(mContext);
                    }
                }
                break;
            default:
                if (!JPushInterface.isPushStopped(mContext)) {
                    pushToken = JPushInterface.getRegistrationID(mContext);
                }
                break;
        }
        Log.i(TAG, "==pushToken:" +pushToken+"/type:"+type);
        return pushToken;
    }

    public void registerReceiver() {
        switch (type) {
            case FCM:
                break;
            case Mi:
                break;
            default:
                LJpushReceiver lJpushReceiver = new LJpushReceiver();
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction("cn.jpush.android.intent.REGISTRATION");
                intentFilter.addAction("cn.jpush.android.intent.MESSAGE_RECEIVED");
                intentFilter.addAction("cn.jpush.android.intent.NOTIFICATION_RECEIVED");
                intentFilter.addAction("cn.jpush.android.intent.NOTIFICATION_OPENED");
                intentFilter.addAction("cn.jpush.android.intent.ACTION_RICHPUSH_CALLBACK");
                intentFilter.addAction("cn.jpush.android.intent.CONNECTION");
                intentFilter.addCategory(mContext.getPackageName());
                mContext.registerReceiver(lJpushReceiver, intentFilter);
                break;
        }
    }

    public void startPush() {
        switch (type) {
            case FCM:
                break;
            case Huawei:
                if (!configuration.hwAppId.equals("")){
                    LHuaweiManger.Companion.startPush(mContext);
                }
                break;
            case Mi:
                if (!configuration.xmAppId.equals("")){
                    LMiManger.Companion.startPush(mContext);
                }
                break;
            case OPPO:
                if (!configuration.oppoAppId.equals("")){
                    LOppoManger.Companion.startPush(mContext);
                }
                break;
            case VIVO:
                if (!configuration.vivoAppId.equals("")){
                    LVivoManger.Companion.startPush(mContext);
                }
                break;
            default:
                LJpushManager.startPush(mContext);
                break;
        }
    }

    public void stopPush() {
        switch (type) {
            case FCM:
                break;
            case Huawei:
                if (!configuration.hwAppId.equals("")){
                    LHuaweiManger.Companion.stopPush(mContext);
                }
                break;
            case Mi:
                if (!configuration.xmAppId.equals("")){
                    LMiManger.Companion.stopPush(mContext);
                }
                break;
            case OPPO:
                if (!configuration.oppoAppId.equals("")){
                    LOppoManger.Companion.stopPush(mContext);
                }
                break;
            case VIVO:
                if (!configuration.vivoAppId.equals("")){
                    LVivoManger.Companion.stopPush(mContext);
                }
                break;
            default:
                LJpushManager.stopPush(mContext);
                break;
        }
    }

    /**
     * 设置标签（对应FCM的主题）
     *
     * @param tags
     */
    public void setTag(String... tags) {
        switch (type) {
            case FCM:
                for (String tag : tags) {
                    setSubscribeToTopic(tag);
                }
                break;
            case Huawei:

                break;
            default:
                LJpushManager.setTag(mContext, tags);
                break;
        }
    }

    /**
     * 删除标签（对应FCM的主题）
     *
     * @param tags
     */
    public void deleteTag(String... tags) {
        switch (type) {
            case FCM:
                for (String tag : tags) {
                    setUnsubscribeToTopic(tag);
                }
                break;
            default:
                LJpushManager.deleteTag(mContext, tags);
                break;
        }
    }

    public void onResume() {
        switch (type) {
            case JPush:
                JPushInterface.onResume(mContext);
                break;
            case Huawei:
                if (!configuration.hwAppId.equals("")){
                    LHuaweiManger.Companion.startPush(mContext);
                }
                break;
            case Mi:
                if (!configuration.xmAppId.equals("")){
                    LMiManger.Companion.startPush(mContext);
                }
                break;
            case OPPO:
                if (!configuration.oppoAppId.equals("")){
                    LOppoManger.Companion.startPush(mContext);
                }
                break;
            case VIVO:
                if (!configuration.vivoAppId.equals("")){
                    LVivoManger.Companion.startPush(mContext);
                }
                break;
        }
    }

    public void onPause() {
        switch (type) {
            case JPush:
                JPushInterface.onPause(mContext);
                break;
            case Huawei:
                if (!configuration.hwAppId.equals("")){
                    LHuaweiManger.Companion.stopPush(mContext);
                }
                break;
            case Mi:
                if (!configuration.xmAppId.equals("")){
                    LMiManger.Companion.stopPush(mContext);
                }
                break;
            case OPPO:
                if (!configuration.oppoAppId.equals("")){
                    LOppoManger.Companion.stopPush(mContext);
                }
                break;
            case VIVO:
                if (!configuration.vivoAppId.equals("")){
                    LVivoManger.Companion.stopPush(mContext);
                }
                break;
        }
    }

    public void setAlias(String alias) {
        LJpushManager.setAlias(mContext, alias);
    }

    public void setSubscribeToTopic(String theme) {
        FirebaseMessaging.getInstance().subscribeToTopic(theme);
    }

    public void setUnsubscribeToTopic(String theme) {
        FirebaseMessaging.getInstance().unsubscribeFromTopic(theme);
    }

    public LRomUtil.ROM_TYPE getType() {
        return type;
    }


    public void onMsgReceiver(PMessage pMessage, boolean custom) {
        configuration.getNotificationListner().receiveMsg(pMessage);
        if (custom) {
            configuration.getNotificationListner().CumtosReceiveMsg(pMessage);
        } else {
            if (!configuration.isCustomNotification()) {
                if (pMessage.getFromType() == 1) {
                    createNotification(pMessage);
                }
            } else {
                configuration.getNotificationListner().CumtosReceiveMsg(pMessage);
            }
        }
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param pMessage
     */
    private void createNotification(PMessage pMessage) {
        Log.d(TAG, "createNotification pack:" + mContext.getPackageName());
        String clear = pMessage.getClean();
        String imgUrl = pMessage.getBigThumb();
        String content = pMessage.getContent();
        String title = pMessage.getTitle();
        if (title == null || title.equals("") || content == null) {
            return;
        }

        Intent intent = new Intent(mContext, configuration.getOpenClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("push_message", ParcelablesUtil.toByteArray(pMessage));
        intent.putExtra("push_type", "1");
        //intent.setPackage(mContext.getPackageName());
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 1, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext)
                .setSmallIcon(configuration.getSmallIcon())
                .setContentTitle(title)
                .setTicker("")
                .setContentText(content)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setPriority(configuration.getPriority())
                .setChannelId(configuration.getChannelId())
                .setColor(configuration.getColor() == -1 ? 0 : configuration.getColor())
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), configuration.getLargeIcon()))
                .setContentIntent(pendingIntent);

        if (clear != null && clear.equals("1")) {
            notificationBuilder.setOngoing(true);
        } else {
            notificationBuilder.setOngoing(false);
        }
        if (imgUrl != null && !imgUrl.equals("")) {
            NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
            Bitmap bitmap = LBitmapUtil.getBitmap(imgUrl);
            style.bigLargeIcon(bitmap);
            style.bigPicture(bitmap);
            notificationBuilder.setStyle(style);
        }

        NotificationManager notificationManager =
                (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT > 25) {
            NotificationChannel channel = new NotificationChannel(configuration.getChannelId(), mContext.getPackageName(), NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(channel);
        }

        String id = System.currentTimeMillis() + "";
        if (id.length() >= 9) {
            notificationManager.notify(Integer.parseInt(id.substring(id.length() - 9)), notificationBuilder.build());
        } else {
            notificationManager.notify(Integer.parseInt(id), notificationBuilder.build());
        }
    }

    public void onNotificationClicked(PMessage pMessage) {
        if (configuration.isCustomNotification()) {
            configuration.getNotificationListner().openMsg(pMessage);
        } else {
            if (configuration.getOpenClass() != null) {
                Intent intent = new Intent(mContext, configuration.getOpenClass());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("push_message", pMessage);
                mContext.startActivity(intent);
            } else {
                Log.d(TAG, "开启页未设置");
            }
        }
    }

}
